<template>
  <div>
    customRef: {{ obj }}
    <br /><br />
    <button @click="change">点击我修改customRef的值</button>
    <br /><br />
    reactive: {{ man }}<br /><br />
    toRef: {{ like }}
    <button @click="change2">点击我修改reactive的值</button>
    <br /><br />
    {{ name }} -- {{ age }}
    <button @click="change3">点击我修改toRefs解构出来的值</button>
  </div>
</template>

<script setup lang="ts">
import { customRef, reactive, toRef } from 'vue';
// 定义自己的ref响应式

type M = {
  name:string,
  age:number
}


function MyRef<T>(value:T) {
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },

      set(newValue) {
        value = newValue
        trigger()
      }
    }
  })
}

const change = () => {
  obj.value = '大满'
}

const obj = MyRef<string>('小满')

const man = reactive<M>({
  name:'天弦',
  age:22
})
// toRef用于解构对象 保证解构后对象的值仍是响应式数据
const like = toRef(man, 'name')

const change2 = () => {
  like.value = '命轮'
  console.log(like)
  
}

const toRefs = <T extends object>(object: T) => {
  const map:any = {}
  for (let key in object) {
    map[key] = toRef(object, key)
  }
  return map
}

const { name, age } = toRefs(man)

const change3 = () => {
  name.value = '命轮',
  age.value = 23
}
</script>

<style scoped></style>
